package com.wulis.common.utils;

import com.wulis.common.model.entity.Node;

import java.util.ArrayList;
import java.util.List;

/**
 * List转Tree工具类
 * 
 * @author WuliBao
 */
public class NodeUtil {

    /**
     * 转换成树
     *
     * @param list list
     * @param <T> <T>
     * @return T
     */
    public static <T extends Node<T>> List<T> buildTree(List<T> list) {
        List<T> tree = new ArrayList<>();
        for (T node : list) {
            if (Long.valueOf(0L).equals(node.getParentId())) {
                tree.add(findNode(node, list));
            }
        }
        return tree;
    }

    /**
     * 递归方式找寻子节点
     *
     * @param node node
     * @param list list
     * @param <T> <T>
     * @return T
     */
    private static <T extends Node<T>> T findNode(T node, List<T> list) {
        for (T n : list) {
            if (n.getParentId().equals(node.getId())) {
                if (node.getNodes() == null) {
                    node.setNodes(new ArrayList<>());
                }
                node.getNodes().add(findNode(n, list));
            }
        }
        return node;
    }
}
